<template>
  <div>
    <!-- 加载动画 -->
    <div v-if="isLoading" class="flex justify-center items-center py-12 animate-fade-in">
      <LoadingAnimation />
    </div>
    
    <!-- 装饰元素 -->
    <div class="absolute top-20 left-10 w-32 h-32 rounded-full bg-gradient-to-r from-indigo-500/10 to-purple-500/10 blur-3xl pointer-events-none"></div>
    <div class="absolute bottom-20 right-10 w-40 h-40 rounded-full bg-gradient-to-r from-blue-500/10 to-indigo-500/10 blur-3xl pointer-events-none"></div>
    
    <!-- 装饰性图标 -->
    <div class="absolute top-10 right-20 opacity-30 pointer-events-none">
      <DecorativeIcon type="star" />
    </div>
    <div class="absolute bottom-10 left-20 opacity-30 pointer-events-none">
      <DecorativeIcon type="lightning" />
    </div>
    <div class="absolute top-1/2 left-5 opacity-30 pointer-events-none">
      <DecorativeIcon type="news" />
    </div>
    <div class="absolute top-1/3 right-5 opacity-30 pointer-events-none">
      <DecorativeIcon type="dot" />
    </div>
    
    <div v-if="!isLoading">
    <el-row :gutter="20" class="animate-fade-in">
      <el-col v-for="(source, index) in newsSources" :key="source.id" :xs="24" :sm="12" :md="8" :lg="6" :style="{'animation-delay': index * 0.1 + 's'}">
        <el-card
          class="mb-6 transition-all duration-300 transform hover:-translate-y-2 hover:shadow-lg hover:border-t-indigo-500 source-card"
          shadow="hover"
        >
          <template #header>
            <div class="flex justify-between items-center relative">
              <div class="absolute -left-2 -top-2 w-8 h-8 rounded-full bg-indigo-500 opacity-10 blur-md"></div>
              <div class="absolute -right-1 -top-1 scale-75 opacity-50 pointer-events-none">
                <DecorativeIcon type="star" :animate="false" />
              </div>
              <span class="font-bold text-lg source-title">{{ source.name }}</span>
              <el-button 
                text 
                @click="viewSourceDetail(source)" 
                class="view-more-btn"
              >
                查看更多
              </el-button>
            </div>
          </template>
          <ol class="list-none p-0 m-0 news-list relative">
            <div class="absolute -right-2 -bottom-2 w-12 h-12 rounded-full bg-indigo-500 opacity-10 blur-md"></div>
            <li v-for="(item, index) in source.news" :key="item.id" class="py-2 border-b border-slate-200 last:border-b-0 news-item">
                              <a :href="`/news/${item.id}`" target="_blank" class="flex items-start no-underline text-current hover:text-indigo-600 w-full transition-colors duration-300">
                <span class="mr-2 font-medium flex-shrink-0 news-index">{{ index + 1 }}.</span>
                <div class="flex-1 min-w-0 flex items-center justify-between">
                  <span class="block truncate font-medium news-title hover-effect" :title="item.title">{{ item.title }}</span>
                  <!-- 热门图标 -->
                  <div v-if="item.isHot" class="ml-2 flex-shrink-0">
                    <el-icon class="hot-icon text-sm hover:scale-110 transition-transform duration-200" title="热门新闻">
                      <svg viewBox="0 0 1024 1024" class="w-4 h-4">
                        <path d="M512 64l128 256 288 32-224 224 64 288-256-128-256 128 64-288-224-224 288-32z" fill="#ff6b35"/>
                      </svg>
                    </el-icon>
                  </div>
                </div>
              </a>
            </li>
          </ol>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- ChatBI 功能区域 -->
    <div class="chatbi-section animate-fade-in" style="animation-delay: 0.5s">
      <el-card class="chatbi-card" shadow="hover">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="flex items-center gap-3">
              <div class="chatbi-icon">🤖</div>
              <div>
                <h3 class="chatbi-title">AI 数据分析助手</h3>
                <p class="chatbi-subtitle">智能分析新闻数据，生成洞察报告</p>
              </div>
            </div>
            <el-button 
              type="primary" 
              size="large" 
              @click="openChatBI"
              class="chatbi-btn"
            >
              <el-icon class="mr-2"><svg viewBox="0 0 1024 1024" class="w-5 h-5"><path d="M512 64l128 256 288 32-224 224 64 288-256-128-256 128 64-288-224-224 288-32z" fill="currentColor"/></svg></el-icon>
              开始分析
            </el-button>
          </div>
        </template>
        
        <div class="chatbi-features">
          <div class="feature-grid">
            <div class="feature-item">
              <div class="feature-icon">📊</div>
              <h4>智能图表</h4>
              <p>自动生成柱状图、折线图、饼图等可视化图表</p>
            </div>
            <div class="feature-item">
              <div class="feature-icon">🔍</div>
              <h4>数据洞察</h4>
              <p>AI分析数据趋势，提供深度洞察和总结</p>
            </div>
            <div class="feature-item">
              <div class="feature-icon">💬</div>
              <h4>自然语言</h4>
              <p>用自然语言提问，AI自动生成SQL查询</p>
            </div>
            <div class="feature-item">
              <div class="feature-icon">⚡</div>
              <h4>实时分析</h4>
              <p>流式处理，实时显示分析进度和结果</p>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    </div>
    
    <!-- ChatBI 模态框 -->
    <BiModal v-model="showChatBI" />
  </div>
</template>

<script setup>
import { ref, computed, inject, onMounted, watch } from 'vue'
import { sourceAPI, newsAPI } from '~/services/api'
import LoadingAnimation from '~/components/LoadingAnimation.vue';
import DecorativeIcon from '~/components/DecorativeIcon.vue';
import BiModal from '~/components/BiModal.vue';

// 获取分类筛选状态
const activeCategory = inject('activeCategory', ref('all'))
const isLoading = ref(true);
const newsSources = ref([]);
const categories = ref([]);

// ChatBI 相关状态
const showChatBI = ref(false);

// 打开ChatBI模态框
const openChatBI = () => {
  showChatBI.value = true;
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取分类ID
const getCategoryId = (categoryKey) => {
  if (categoryKey === 'all') return null
  // 优先使用分类 code，其次使用 id
  const category = categories.value.find(cat => cat.code === categoryKey || String(cat.id) === String(categoryKey))
  return category ? category.id : null
}

// 加载数据
const loadData = async () => {
  try {
    isLoading.value = true
    
    // 并行加载分类和信源卡片数据
    const [categoriesData, sourceCardsData] = await Promise.all([
      sourceAPI.getCategories(),
      sourceAPI.getSourceCards()
    ])
    
    categories.value = categoriesData || []
    
    // 初始化信源结构（容错：若无卡片数据则退化为信源列表）
    const baseSources = (sourceCardsData && sourceCardsData.length)
      ? sourceCardsData
      : await sourceAPI.getSources()
    
    newsSources.value = (baseSources || []).map(source => ({
      id: source.id,
      name: source.name,
      homepage: source.homepage,
      regionName: source.regionName,
      newsCount: source.newsCount ?? 0,
      news: []
    }))
    
    console.log('初始化信源数量:', newsSources.value.length)
    
    // 根据当前分类筛选加载新闻数据
    await loadNewsData()
    
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 加载新闻数据
const loadNewsData = async () => {
  try {
    const categoryId = getCategoryId(activeCategory.value)
    
    // 为每个信源加载新闻数据
    const newsPromises = newsSources.value.map(async (source) => {
      try {
        const params = { limit: 10 } // 每个信源最多10条
        if (categoryId) {
          params.categoryId = categoryId
        }
        
        const newsData = await newsAPI.getNewsBySource(source.id, params)
        console.log(`信源 ${source.name} (ID: ${source.id}) 加载了 ${newsData.length} 条新闻`)
        return {
          ...source,
          news: newsData
        }
      } catch (error) {
        console.error(`加载信源 ${source.name} 的新闻失败:`, error)
        return {
          ...source,
          news: []
        }
      }
    })
    
    const updatedSources = await Promise.all(newsPromises)
    newsSources.value = updatedSources.filter(s => s && s.id)
    console.log('各信源加载完成，卡片数量:', newsSources.value.length)
    
  } catch (error) {
    console.error('加载新闻数据失败:', error)
  }
}

// 监听分类变化
watch(activeCategory, () => {
  loadNewsData()
})

// 初始化
onMounted(() => {
  loadData()
})

// 查看信源详情
const viewSourceDetail = (source) => {
  navigateTo(`/source/${source.id}`)
}
</script>

<style scoped>
/* 页面进入动画 */
@keyframes slideInUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.el-row {
  animation: slideInUp 0.6s ease-out;
}
.source-card {
  background-color: var(--light-card);
  border-color: var(--light-border);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.03), 0 1px 3px rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  border-top: 3px solid transparent;
  transition: all 0.3s ease;
  animation: fadeIn 0.5s ease-out forwards;
  position: relative;
  overflow: hidden;
}

.source-card::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(79, 70, 229, 0.1) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.5s ease;
}

.source-card:hover::before {
  opacity: 1;
}

.source-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08), 0 3px 6px rgba(0, 0, 0, 0.12);
  border-top-color: var(--primary-color);
}




.source-title {
  color: var(--light-text);
  font-weight: 600;
}


.view-more-btn:hover {
  color: var(--primary-color);
}


.news-item {
  transition: all 0.3s ease;
  background-color: rgba(241, 245, 249, 0.7);
  margin-bottom: 6px;
  border-radius: 6px;
  padding: 4px 6px;
  border-left: 2px solid transparent;
  position: relative;
  z-index: 1;
  overflow: hidden;
}

.news-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, rgba(79, 70, 229, 0.1) 0%, transparent 100%);
  transform: translateX(-100%);
  transition: transform 0.3s ease;
  z-index: -1;
}


.news-item:hover {
  transform: translateX(4px);
  border-left: 2px solid var(--primary-color);
}

.news-item:hover::before {
  transform: translateX(0);
}




.news-index {
  color: var(--primary-color);
  display: inline-block;
  transition: transform 0.2s ease;
}

.news-item:hover .news-index {
  transform: scale(1.1);
}

.news-title {
  transition: all 0.3s ease;
  display: inline-block;
  position: relative;
  padding: 2px 0;
}

.news-title.hover-effect:hover {
  transform: translateX(12px) scale(1.05);
  color: var(--primary-color);
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.news-title.hover-effect::after {
  content: '';
  position: absolute;
  width: 0;
  height: 1px;
  bottom: 0;
  left: 0;
  background-color: var(--primary-color);
  transition: width 0.3s ease;
}

.news-title.hover-effect:hover::after {
  width: 100%;
}




/* 热门图标独立样式 */
.hot-icon {
  color: #ff6b35 !important;
  filter: drop-shadow(0 1px 2px rgba(255, 107, 53, 0.3));
}

.hot-icon:hover {
  color: #ff8c42 !important;
  filter: drop-shadow(0 2px 4px rgba(255, 107, 53, 0.5));
  transform: scale(1.1);
}

/* ChatBI 功能区域样式 */
.chatbi-section {
  margin-top: 40px;
  margin-bottom: 40px;
}

.chatbi-card {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.chatbi-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border-color: #cbd5e0;
}

.chatbi-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.chatbi-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 700;
  color: #1e293b;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.chatbi-subtitle {
  margin: 0;
  color: #64748b;
  font-size: 14px;
  line-height: 1.5;
}

.chatbi-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.chatbi-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.chatbi-features {
  margin-top: 24px;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.feature-item {
  background: white;
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  text-align: center;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.feature-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.feature-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
  border-color: #cbd5e0;
}

.feature-item:hover::before {
  transform: scaleX(1);
}

.feature-icon {
  font-size: 32px;
  margin-bottom: 16px;
  display: inline-block;
  transition: transform 0.3s ease;
}

.feature-item:hover .feature-icon {
  transform: scale(1.1);
}

.feature-item h4 {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.feature-item p {
  margin: 0;
  color: #64748b;
  font-size: 14px;
  line-height: 1.5;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .chatbi-card .el-card__header {
    padding: 20px;
  }
  
  .chatbi-card .el-card__body {
    padding: 20px;
  }
  
  .feature-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .chatbi-title {
    font-size: 20px;
  }
  
  .chatbi-icon {
    width: 50px;
    height: 50px;
    font-size: 24px;
  }
}
</style>